<?php
/**
 * Created by PhpStorm.
 * User: chenzhitao
 * Date: 2018/4/1
 * Time: 下午6:57
 */

namespace App\Busi\Traits;


use App\Exceptions\ErrorCode\UserError;
use App\Exceptions\UserException;
use App\Models\User;
use App\Util\StringUtil;
use Illuminate\Support\Facades\Cache;

Trait UserTrait
{
     function existsPhone($phone){
        /**
         * 判断手机格式是否正确
         *
         * @param $phone
         * @throws UserException
         */
        if(!StringUtil::isStrValid($phone, StringUtil::MobileString)) {
            UserException::touch(UserError::PHONE_FORMAT_ERROR);
        }
     }

    /**
     * @param $phone
     *
     * @return mixed
     */
     function getUserByPhone($phone)
    {
        $user = User::where('phone', $phone)->first();
        return $user;
    }
    /**
     * @param $phone
     *
     * @return mixed
     */
    function getUserByUid($uid)
    {
        $user = User::where('uid', $uid)->first();
        return $user;
    }
    /**
     * @param $phone
     *
     * @return mixed
     */
    function getUserNameByid($id)
    {
        $where = [
            ["id","=",$id],
            ["flag","=",1]
        ];
        $field = ["id","phone"];
        $data = User::where($where)->select($field)->first();
        if($data){
            return "<a class='success' href='user/".$data['id']."' target='_blank'>{$data['phone']}</a><br>";
        }else{
            return "";
        }

    }
    function setUserLoginStatus($key, $captcha, $ttl = 60*6){
        return Cache::put($key, $captcha, $ttl);
    }
    public function checkUserLoginStatus($key, $value)
    {
        $phone = Cache::get($key);

        if($phone == false || $phone != $value) {
            $data = [
                "msg"=>"登录超时",
                "status" =>-1
            ];
            return $data;

        }
        $data = [
            "msg"=>"登录中",
            "status" =>1
        ];

        return $data;
    }
    function setUserLogout($key){
        $code = Cache::get($key);
        if($code == false) {
            return true;
        }
        Cache::forget($key);
        return true;
    }



}